<template>
  <div>
    <!-- 顶部步骤条 -->
    <div class="top">
      <el-steps :active="active" class="steps" finish-status="success">
        <el-step title="商品基本信息"></el-step>
        <el-step title="添加库存信息"></el-step>
        <el-step title="添加移动端详情"></el-step>
      </el-steps>
    </div>

    <el-card style="margin: 20px">
      <el-form
        label-width="80px"
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        class="ruleForm"
      >
        <!-- 第一页信息 -->
        <div v-if="active == 0">
          <!-- 基本信息 -->
          <div class="info">基本信息</div>
          <el-row :gutter="20" type="flex" justify="space-between">
            <el-col :span="7">
              <el-form-item label-width="100px" label="商品名称">
                <el-input size="mini" v-model="ruleForm.name"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="7">
              <el-form-item label-width="100px" label="商品编码">
                <el-input size="mini" v-model="ruleForm.id"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="7">
              <el-form-item
                label-width="100px"
                label="商品分类"
                prop="productCategoryName"
              >
                <el-select
                  style="width: 90%"
                  size="mini"
                  v-model="ruleForm.productCategoryName"
                  placeholder="商品分类"
                >
                  <el-option label="创意" value="创意"></el-option>
                  <el-option label="风格" value="风格"></el-option>
                  <el-option label="饰品" value="饰品"></el-option>
                  <el-option label="灯具" value="灯具"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item
                label-width="100px"
                label="商品品牌"
                prop="brandName"
              >
                <el-select
                  style="width: 24%"
                  size="mini"
                  v-model="ruleForm.brandName"
                  placeholder="品牌"
                >
                  <el-option
                    v-for="item in brandList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label-width="100px" label="商品描述">
                <el-input
                  style="width: 55%"
                  type="textarea"
                  v-model="ruleForm.description"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 商品属性 -->

          <div class="info">商品属性</div>

          <el-row :gutter="20" type="flex" justify="space-between">
            <el-col :span="8">
              <el-form-item label-width="100px" label="商品原价">
                <el-input-number
                  style="width: 90%"
                  size="mini"
                  v-model="ruleForm.originalPrice"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="100px" label="促销类型">
                <el-select
                  style="width: 90%"
                  size="mini"
                  disabled
                  placeholder="没有促销使用原价"
                  v-model="value"
                ></el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="100px" label="活动价格">
                <el-input-number
                  style="width: 90%"
                  size="mini"
                  disabled
                  v-model="ruleForm.originalPrice"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row type="flex" justify="end">
            <el-col :span="8">
              <el-form-item label-width="100px" label="重量(kg)">
                <el-input-number
                  style="width: 90%"
                  size="mini"
                  v-model="ruleForm.weight"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label-width="100px" label="审核状态">
                <el-switch
                  v-model="ruleForm.verifyStatus"
                  :active-value="1"
                  :inactive-value="0"
                >
                </el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="100px" label="是否上架">
                <el-switch
                  v-model="ruleForm.publishStatus"
                  :active-value="1"
                  :inactive-value="0"
                >
                </el-switch>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20" type="flex" justify="space-between">
            <el-col :span="24">
              <el-form-item label-width="100px" label="缩略图">
                <el-upload
                  class="avatar-uploader"
                  :action="uploadUrl"
                  :show-file-list="false"
                  :headers="uploadHeader"
                  :on-success="getPic"
                >
                  <img v-if="ruleForm.pic" :src="ruleForm.pic" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 其他信息 -->
          <div class="info">其他信息</div>
          <el-row :gutter="20" type="flex" justify="space-between">
            <el-col :span="8">
              <el-form-item label-width="100px" label="推荐状态">
                <el-switch
                  v-model="ruleForm.recommendStatus"
                  :active-value="1"
                  :inactive-value="0"
                >
                </el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="100px" label="新品状态">
                <el-switch
                  v-model="ruleForm.newStatus"
                  :active-value="1"
                  :inactive-value="0"
                >
                </el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="100px" label="预告商品">
                <el-switch
                  v-model="ruleForm.previewStatus"
                  :active-value="1"
                  :inactive-value="0"
                >
                </el-switch>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20" type="flex" justify="space-between">
            <el-col :span="8">
              <el-form-item label-width="100px" label="搜索关键词">
                <el-input size="mini" v-model="ruleForm.keywords"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="100px" label="库存预警">
                <el-input-number
                  style="width: 90%"
                  size="mini"
                  v-model="ruleForm.lowStock"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="100px" label="商品排序">
                <el-input-number
                  style="width: 90%"
                  size="mini"
                  v-model="ruleForm.sort"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 产品服务 -->
          <el-row :gutter="20" type="flex" justify="center">
            <el-col :span="8">
              <el-form-item label-width="100px" label="产品服务">
                <el-checkbox-group v-model="ruleForm.serviceIds">
                  <el-checkbox label="1">无忧退货</el-checkbox>
                  <el-checkbox label="2">快速退款</el-checkbox>
                  <el-checkbox label="3">免费包邮</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 第二页信息 -->
        <div v-if="active == 1">
          <div class="info">商品sku信息</div>
          <el-row :gutter="20" type="flex" justify="space-round">
            <el-col :span="8">
              <el-form-item label-width="100px" label="标题">
                <el-input size="mini" v-model="ruleForm.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="100px" label="副标题">
                <el-input size="mini" v-model="ruleForm.subTitle"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label-width="100px" label="画册图片">
            <el-upload
              :action="uploadUrl"
              :headers="uploadHeader"
              list-type="picture-card"
              :limit="5"
              :file-list="fileList"
              :on-preview="handlePictureCardPreview"
              :on-change="changePic"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-form-item>
          <el-form-item label-width="100px" label="sku设置">
            <el-form-item label-width="50px" label="颜色:">
              <el-checkbox-group v-model="skuList.color.choList">
                <el-checkbox
                  v-for="(item, index) in skuList.color.list"
                  :key="index"
                  :label="item"
                >
                  {{ item }}
                  <el-button
                    style="color: red"
                    type="text"
                    @click="delColor(index)"
                    >删除</el-button
                  >
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label-width="50px" label="大小:">
              <el-checkbox-group v-model="skuList.size.choList">
                <el-checkbox
                  v-for="(item, index) in skuList.size.list"
                  :key="index"
                  :label="item"
                >
                  {{ item }}
                  <el-button
                    style="color: red"
                    type="text"
                    @click="delSize(index)"
                    >删除</el-button
                  >
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-row :gutter="10" type="flex" justify="start">
              <el-col :span="3">
                <el-input
                  size="mini"
                  v-model="skuList.color.text"
                  placeholder="颜色描述:比如土豪金"
                ></el-input>
              </el-col>
              <el-col :span="3">
                <el-button size="mini" @click="addSkuList('color')"
                  >创建颜色选项</el-button
                >
              </el-col>
              <el-col :span="3">
                <el-input
                  size="mini"
                  v-model="skuList.size.text"
                  placeholder="大小"
                ></el-input>
              </el-col>
              <el-col :span="3">
                <el-button size="mini" @click="addSkuList('size')"
                  >创建大小选项</el-button
                >
              </el-col>

              <el-col :span="6" style="margin-left: 50px">
                <el-button type="primary" size="mini" @click="makeList"
                  >生成sku列表</el-button
                >
                <el-button type="primary" size="mini" @click="addList"
                  >新增sku</el-button
                >
              </el-col>
            </el-row>
          </el-form-item>

          <!-- sku列表 -->
          <el-table :data="skuTableList" border style="width: 100%">
            <el-table-column label="#" type="index" width="50">
            </el-table-column>

            <el-table-column label="图片" width="200">
              <template slot-scope="scope">
                <el-upload
                  class="avatar-uploader"
                  :action="uploadUrl"
                  :show-file-list="false"
                  :headers="uploadHeader"
                  :on-success="handleAvatarSuccess"
                  @click.native="getRow(scope.row)"
                >
                  <img
                    v-if="scope.row.pic"
                    :src="scope.row.pic"
                    class="avatar"
                  />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  <div slot="tip" class="el-upload__tip">
                    只能上传jpg/png文件，且不超过500kb
                  </div>
                </el-upload>
              </template>
            </el-table-column>

            <el-table-column label="颜色" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.spData[0].value"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="大小" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.spData[1].value"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="库存" width="250">
              <template slot-scope="scope">
                <el-input v-model="scope.row.stock"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="预警库存" width="250">
              <template slot-scope="scope">
                <el-input v-model="scope.row.lowStock"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="锁定库存" width="250">
              <template slot-scope="scope">
                <el-input v-model="scope.row.lockStock"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="sku编码" width="250">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuCode"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="价格" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.price"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="销量" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.sale"></el-input>
              </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" width="100">
              <template slot-scope="scope">
                <el-button
                  style="color: red"
                  @click="delSkuTableList(scope.row)"
                  type="text"
                  size="small"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 第三页信息 -->
        <div v-if="active == 2">
          <el-card>
            <div class="info">详情描述</div>

            <el-form>
              <el-col :span="24">
                <el-form-item label-width="100px" label="商品详情">
                  <!-- 富文本框 -->
                  <TEditor v-model="ruleForm.detailHtml" />
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label-width="100px" label="备注">
                  <el-input
                    type="textarea"
                    v-model="ruleForm.note"
                    placeholder="备注"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-form>
          </el-card>
        </div>

        <div class="isButton">
          <el-button
            v-if="active == 1 || active == 2"
            size="mini"
            @click="goprev"
            >返回上一步</el-button
          >
          <el-button v-if="active == 0" size="mini" type="primary" @click="next"
            >下一步,填写库存信息</el-button
          >
          <el-button v-if="active == 1" size="mini" type="primary" @click="next"
            >下一步,填写移动端详情</el-button
          >
          <el-button
            v-if="active == 2"
            size="mini"
            type="primary"
            @click="addSave"
            >提交保存</el-button
          >
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {
  findAllBrand,
  addProductAndSkus,
  productSkusDetail,
  updateProductAndSkus
} from '@/api/product/list'
import TEditor from '@/components/Tinymce/index'
import mixin from '@/mixins/index'
export default {
  mixins: [mixin],
  components: {
    TEditor
  },
  data() {
    return {
      //接收来自编辑的id
      fromId: '',
      //接收来自编辑的商品数据
      fromList: [],
      //步骤条被选中
      active: 0,
      //品牌列表数据
      brandList: [],
      //上传商品的数组
      ruleForm: {
        //商品名称
        name: '',
        //商品编码
        id: '',
        //商品分类
        productCategoryName: '',
        //商品品牌
        brandName: '',
        //商品原价
        originalPrice: '',
        //重量
        weight: 0,
        //审核状态
        verifyStatus: 0,
        //是否上架
        publishStatus: 0,
        // 推荐状态
        recommendStatus: 0,
        //新品状态
        newStatus: 0,
        //预告商品
        previewStatus: 0,
        //搜索关键词
        keywords: '',
        // 库存预警
        lowStock: '',
        // 商品排序
        sort: 0,
        //产品服务
        serviceIds: [],
        //备注
        note: '',
        //画册图片
        albumPics: '',
        // 缩略图
        pic: ''
      },
      //图片列表
      fileList:[],
      value: 0,
      //校验规则
      rules: {
        name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }]
      },
      //新增sku相关
      skuList: {
        // sku颜色
        color: {
          text: '',
          list: [], //颜色类别
          choList: [] // 被选中的颜色
        },
        // sku大小
        size: {
          text: '',
          list: [], //大小类别
          choList: [] // 被选中的大小
        }
      },
      skuInfo: [], // 拼接后的数据
      skuTableList: [], //渲染到Table中的数据
      skuTempId: '', //临时行id
      dialogImageUrl: '',
      dialogVisible: false,
      picList: [] //画册图片临时数组
    }
  },
  created() {
    this.getBrand()
    if (this.$route.query.id) {
      this.fromId = this.$route.query.id
      this.forEdit()
    }
  },
  methods: {
    //是否由编辑按钮进入
    forEdit() {
      productSkusDetail(this.fromId).then((res) => {
        // console.log(res)
        res.data.product.serviceIds = res.data.product.serviceIds.split(',')
        console.log(res.data.product.serviceIds)
        this.ruleForm = res.data.product
        const imgArr = this.ruleForm.albumPics.split(',')
        imgArr.forEach((item) => {
            this.fileList.push({
                url: item
            })
        })
        console.log(res.data.skus);
        this.skuTableList = res.data.skus
        console.log(this.ruleForm)
        res.data.skus.forEach((val) => {
        val.spData = JSON.parse(val.spData)
        })
      })
    },
    // 提交保存
    addSave() {
      if (this.fromId) {
        this.skuTableList.temId = ''
        if (this.ruleForm.serviceIds.length > 0) {
          var list = this.ruleForm.serviceIds.join(',')
        }
        console.log(this.skuTableList);
        this.skuTableList.forEach((res) => {
          res.spData = JSON.stringify(res.spData)
        })
        // console.log(this.skuTableList)
        // console.log(this.ruleForm)
        this.ruleForm.serviceIds = ''
        this.ruleForm.serviceIds =  list
        //
        updateProductAndSkus({
          pmsSkuStockList: this.skuTableList,
          product: this.ruleForm
        }).then((res) => {
          console.log(res)
          this.$router.push({ name: 'List' })
        })
        
      } else {
        this.skuTableList.temId = ''
        if (this.ruleForm.serviceIds.length > 0) {
          var list = this.ruleForm.serviceIds.join(',')
        }
        this.skuTableList.forEach((res) => {
          res.spData = JSON.stringify(res.spData)
        })
        console.log(this.skuTableList)
        console.log(this.ruleForm)
        this.ruleForm.serviceIds = ''
        this.ruleForm.serviceIds = list
        addProductAndSkus({
          pmsSkuStockList: this.skuTableList,
          product: this.ruleForm
        }).then((res) => {
          console.log(res)
        })
        this.$router.push({name:"List"})
      }
    },
    // 画册图片回调
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    getPic(res, file) {
      if (res.success) {
        this.ruleForm.pic = res.data.fileUrl
        this.$message.success('上传图片成功')
      } else {
        this.$message.error('上传图片失败')
      }
    },

    //画册图片改变事件
    changePic(file, fileList) {
      var list = []
      fileList.forEach((res) => {
        var el = res.url.replace('blob', '')
        list.push(el)
      })
      this.ruleForm.albumPics = list.join(',')
    },
    //获取品牌列表
    getBrand() {
      findAllBrand().then((res) => {
        this.brandList = res.data.items
        console.log(res)
      })
    },

    //步骤条下一步
    next() {
      if (this.active++ > 2) this.active = 0
    },
    //步骤条上一步
    goprev() {
      this.active--
    },
    //创建颜色或大小
    addSkuList(skuName) {
      var same = this.skuList[skuName].list.every(
        (res) => res !== this.skuList[skuName].text
      )
      if (same) {
        if (this.skuList[skuName].text) {
          this.skuList[skuName].list.push(this.skuList[skuName].text)
          this.skuList[skuName].text = ''
        }
      } else {
        this.$message.error('不能输入相同的值')
      }
    },
    // 删除颜色
    delColor(val) {
      this.skuList.color.list.splice(val, 1)
    },
    //删除大小
    delSize(val) {
      this.skuList.size.list.splice(val, 1)
    },
    // 生成sku
    makeList() {
      if (this.skuList.color.choList.length != 0) {
        this.$confirm('此操作将清空sku列表,并生成新的列表, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.skuTableList = []
          this.addList()
        })
      } else {
        this.$message.error('选择颜色')
      }
    },
    //新增sku
    addList() {
      var list = [
        ...[this.skuList.color.choList],
        ...[this.skuList.size.choList]
      ]
      // console.log(list);
      //拼接sku列表
      this.skuInfo = list.reduce((total, current) => {
        var skuInfo = []
        total.forEach((res) => {
          current.forEach((val) => {
            skuInfo.push([res, val])
          })
        })
        return skuInfo
      })
      this.createSkuTable()
    },
    //生成skuTable列表
    createSkuTable() {
      this.skuInfo.forEach((item, index) => {
        var obj = {
          lockStock: 0,
          lowStock: 0,
          price: 0,
          sale: '',
          skuCode: '100000',
          stock: 0,
          pic: '', //上传图片
          spData:[
            {key: '颜色', value:item[0]}, //上传颜色 第二个
            {key: '大小', value:item[1]} //上传大小 第一个
          ], 
          temId: index
        }
        this.skuTableList.push(Object.assign({}, obj)) //将obj浅拷贝过来
      })
    },
    //上传图片
    handleAvatarSuccess(res, file) {
      console.log(res)
      if (res.success) {
        this.skuTableList.forEach((item) => {
          if (item.temId == this.skuTempId) {
            item.pic = res.data.fileUrl
            this.$message.success('上传图片成功')
          }
        })
        this.skuTempId = ''
      } else {
        this.$message.error('上传图片失败')
      }
    },
    //全局声明当前行id
    getRow(val) {
      console.log(val)
      this.skuTempId = val.temId
    },
    // 删除sku列表数据
    delSkuTableList(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.skuTableList = this.skuTableList.filter(
          (res) => res.temId != row.temId
        )
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    }
  }
}
</script>
<style lang="scss">
.el-form-item__label {
  font-weight: 400;
}
</style>

<style lang="scss" scoped>
.app-main {
  font-size: 14px;
}
//步骤条
.top {
  background-color: #fff;
  padding-bottom: 20px;
}
.steps {
  width: 60%;
  margin: 0 auto;
}
//基本信息
.info {
  padding: 10px 0;
  border-bottom: 1px solid #e5e5e5;
  margin-bottom: 30px;
  font-size: 16px;
}
.isButton {
  margin: 0 auto;
  text-align: center;
  margin-top: 12px;
}
// 上传图片样式
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>